﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HgRemoteContracts;
using System.ServiceModel;

namespace HgRemote
{
	public class Client : IHgCallback
	{
		private static DuplexChannelFactory<IHgServer> factory;
		private static IHgCallback currentResponseTarget;

		private Client()
		{
		}

		static Client()
		{
			try
			{
				Client c = new Client();
				InstanceContext context = new InstanceContext(c);
				factory = new DuplexChannelFactory<IHgServer>(context, "HgRemoteServer");
			}
			catch (Exception x)
			{
				Console.WriteLine(x.Message);
			}
		}

		public static IHgServer Current
		{
			get
			{
				return factory.CreateChannel();
			}
		}

		public void SendResponse(string content)
		{
			var target = currentResponseTarget;
			if (target != null)
				target.SendResponse(content);
		}

		public void Finished()
		{
			var target = currentResponseTarget;
			if (target != null)
				target.Finished();
			currentResponseTarget = null;
		}

		public static void SetResponseTarget(IHgCallback newTarget)
		{
			currentResponseTarget = newTarget;
		}
	}

}
